﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CreateBranchPipe : HYExternalCommand
	{
		public override Result HYExecute(ref string tranName)
		{
			tranName = "创建排水支管";
			ISelectionFilter selectionFilter = new FixturesFilter();
			IEnumerable<Element> enumerable = base.Sel.PickElementsByRectangle(selectionFilter, "请框选需要创建支管的器具");
			List<XYZ> list = new List<XYZ>();
			List<Connector> list2 = new List<Connector>();
			foreach (Element element in enumerable)
			{
				Connector elementOutConnector = YJKRevitTools.GetElementOutConnector(element, (Autodesk.Revit.DB.Domain)3);
				if (elementOutConnector != null)
				{
					list2.Add(elementOutConnector);
				}
				else
				{
					list.Add((element.Location as LocationPoint).Point);
				}
			}
			if (base.Doc.ActiveView.GenLevel == null)
			{
				YJKMessageBox.Information("必须在平面视图下才能创建");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			double elevation = base.Doc.ActiveView.GenLevel.Elevation;
			HYDrainageSystemSetting instance = HYDrainageSystemSetting.Instance;
			instance.InitialPipeSystemType(base.Doc);
			PipeType hypipeType = instance.HYPipeType;
			PipingSystemType pipingSystemType = instance.PipingSystemType;
			HYCreatePipeHelper hycreatePipeHelper = new HYCreatePipeHelper();
			foreach (XYZ xyz in list)
			{
				double num = 100.0;
				XYZ distancePoint = this.GetDistancePoint(xyz, elevation);
				hycreatePipeHelper.DrawRiserPipe(xyz, distancePoint, base.Doc, hypipeType, num.ToString(), pipingSystemType);
			}
			foreach (Connector connector in list2)
			{
				double num = NumbericTools.feetTomm(connector.Radius * 2.0);
				XYZ distancePoint2 = this.GetDistancePoint(connector.Origin, elevation);
				Pipe elem = hycreatePipeHelper.DrawRiserPipe(connector.Origin, distancePoint2, base.Doc, hypipeType, num.ToString(), pipingSystemType);
				YJKRevitTools.ConnectTwoElement(connector, elem);
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private XYZ GetDistancePoint(XYZ sPoint, double level)
		{
			new XYZ();
			return sPoint + new XYZ(0.0, 0.0, -1.0) * this.GetHeightLevel(sPoint, level);
		}

		private double GetHeightLevel(XYZ xyz, double level)
		{
			double num = xyz.Z - level;
			if (num < -0.001)
			{
				num = 0.0;
			}
			return num + NumbericTools.mmToFeet(150.0);
		}
	}
}
